package com.koron.css2.clientCenter.impl;

import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.BaseReceiptAccessoryMapper;
import com.koron.css2.clientCenter.bean.CheckOpenItem;
import com.koron.css2.clientCenter.bean.OpenUserAddBillBean;
import com.koron.css2.clientCenter.bean.UserOpenBean;
import com.koron.css2.clientCenter.mapper.OpenUserMapper;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.swan.bean.MessageBean;

import java.util.*;
import java.util.stream.Collectors;
/**
 * 添加开户单据
 * 参数-详情列表id
 * @author LGC
 *
 */
public class OpenUserAddBill implements ServerInterface {

	@Override
	@Transactional(rollbackFor = Exception.class)
	public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
		// TODO Auto-generated method stub
		OpenUserMapper mapper = factory.getMapper(OpenUserMapper.class);
		MsInfoMapper msInfoMapper = factory.getMapper(MsInfoMapper.class);
		try {
			OpenUserAddBillBean bean = JsonUtils.objectToPojo(req.getData(), OpenUserAddBillBean.class);
			List<String> list = bean.getList();
			if(list.size()==0) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "未添加开户列表数据，保存失败", null);
			}
			String id = bean.getId();
			List<CheckOpenItem> checkList = mapper.checkItemNull(list);
			String msg = checkList(checkList);
			if(msg!=null) {
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, msg, null);
			}
			//判断水表信息是否重复
			if (compareData(checkList)){
				return MessageBean.create(Constant.MESSAGE_INT_FAIL, "水表编号重复使用，请返回修改", null);
			}
			if(StringUtils.isBlank(bean.getId())) {
				//第一条数据
				UserOpenBean userOpen = mapper.getUserOpenListInfoByDetailId(list.get(0));
				userOpen.setCreateInfo(userInfo);
				userOpen.setBillNo(Tools.getBillNo(factory, "USER_OPEN"));
				userOpen.setBillDate(Tools.getCurrentDate());
				mapper.userOpenAdd(userOpen);//保存到单据上
				mapper.updateDetail(list, userOpen.getId());
				id=userOpen.getId(); 
				BaseReceiptAccessoryMapper accessoryMapper = factory.getMapper(BaseReceiptAccessoryMapper.class);
				if(!StringUtils.isBlank(bean.getTempId()))	{
					//修改附件ID
					accessoryMapper.updateAccessoryReceiptId(id, bean.getTempId());
				}
				//新数据，直接修改水表状态
				List<String> meterNos = checkList.stream().map(CheckOpenItem::getMeterNo).collect(Collectors.toList());
				meterNos.forEach(meterNo->{
					msInfoMapper.updateMsInfoStatus(meterNo,2);
				});
			}else {
				mapper.updateDetail(list, bean.getId());
			}
			@SuppressWarnings("rawtypes")
			MessageBean<Map> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "执行成功", Map.class);
			Map<String, String> map = new HashMap<String, String>();
			map.put("id", id);
			
			info.setData(map);
			return info;
		}catch (Exception e) {
			// TODO: handle exception
			logger.error("开户失败", e);
			return MessageBean.create(Constant.MESSAGE_INT_FAIL, "添加开户单据失败", void.class);
		}
		
	}
	public String checkList(List<CheckOpenItem> checkList) {
		for (CheckOpenItem item : checkList) {
			if(StringUtils.isAnyEmpty(item.getCertNo(),item.getAccountType()
					,item.getBusinessArea(),item.getCertType(),item.getCtmAddr()
					,item.getCtmName(),item.getCtmType(),item.getMeterNo()
					,item.getMeterType(),item.getMeterUse(),item.getPayWay(),item.getSetupMeterDate(),item.getUseWaterObject()
					,item.getUseWaterType(),item.getVatFlag(),item.getOutNo())) {
				return "用户编号："+item.getUserNo()+"，必填信息不完整";
			}
			if("1".equals(item.getPayWay()) && StringUtils.isAnyEmpty(item.getOpenAccountBank(),item.getOpenAccountName(),item.getBankAccount())) {
				return "用户编号："+item.getUserNo()+"，必填信息不完整";
			}
			if("2".equals(item.getPayWay()) && StringUtils.isAnyEmpty(item.getOpenAccountBank(),item.getOpenAccountName()
					,item.getBankAccount(),item.getEntrustContract(),item.getEntrustNo())) {
				return "用户编号："+item.getUserNo()+"，必填信息不完整";
			}
		}
		return null;
	}

	/**
	 * 判断开户水表编号是否有重复，有重复true
	 *
	 * @param list
	 * @return
	 */
	private Boolean compareData(List<CheckOpenItem> list) {
		Set<CheckOpenItem> set = new TreeSet<CheckOpenItem>(new Comparator<CheckOpenItem>() {
			@Override
			public int compare(CheckOpenItem a, CheckOpenItem b) {
				// 字符串则按照asicc码升序排列
				return a.getMeterNo().compareTo(b.getMeterNo());
			}
		});
		set.addAll(list);
		if (set.size() < list.size()) {
			return true;
		}
		return false;
	}
}
